package boerse.CommandProcessor;

import boerse.main.Exceptions.FalseCommandException;
import boerse.main.Exceptions.FalseParametersException;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;

public class CommandScanner {	

	private BufferedReader reader;
	private CommandTypeInfo[] commands;

	public CommandScanner(CommandTypeInfo[] commands ,BufferedReader reader) {
		this.reader = reader;
		this.commands = commands;
	}
	
	public void fillInCommandDesc(CommandDescriptor commandDescriptor) throws FalseCommandException, FalseParametersException {
		try {
			String s = this.reader.readLine().toLowerCase();
			String[] input = s.split(" ");
			Object[] commandAndParams = new Object[input.length];
			
			ArrayList<CommandTypeInfo> possibleCommands = new ArrayList<CommandTypeInfo>();
			
			for (int i = 0; i < commands.length; i++) {
				if (input[0].equals(commands[i].getCmdAbbreviation())) {
					possibleCommands.add(commands[i]);
				}
			}
			
			if (possibleCommands.size() == 0)
				throw new FalseCommandException();
			
			
			Class<?>[] params = {};
			
			for (CommandTypeInfo command : possibleCommands) {
				params =  command.getParamTypes();
				
				if (params.length == 0 && input.length - 1 == 0) {
					commandAndParams[0] = command;
					commandDescriptor.setObject(commandAndParams);
					return;
				}
				
				else if (params.length != input.length-1) {	
					continue;
				}
		
				if (command.getParamTypes().length == input.length - 1) {					
					commandAndParams[0] = command;
					for (int i = 0; i < params.length; i++) {
						if (params[i].equals(String.class)) {
							commandAndParams[i+1] = input[i+1];
							if (i+1 == params.length) {
								commandDescriptor.setObject(commandAndParams);
								return;
							}
						}
						else if (params[i].equals(int.class)) {
							try {
							commandAndParams[i+1] = Integer.parseInt(input[i+1]);
							if (i+1 == params.length) {
								commandDescriptor.setObject(commandAndParams);
								return;
							}
							} catch (NumberFormatException e) {
								break;
							}
						}
						else
							continue;
						
						}
				}
			}
			
			throw new FalseParametersException();
			
		} catch (NumberFormatException e) {
			throw new FalseParametersException();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	
}
